<template>
  <div class="orders-list">
    <el-row class="filter-bar">
      <el-col :span="24">
        <div class="left">
          <el-select
            v-model="classify"
            placeholder="请选择"
            clearable>
            <el-option label="全部" value="4"></el-option>
            <el-option label="贬损者" value="0"></el-option>
            <el-option label="被动者" value="1"></el-option>
            <el-option label="推荐者" value="2"></el-option>
            <el-option label="未分类" value="3"></el-option>
          </el-select>
          <el-date-picker
            class="date-picker mgr10"
            v-model="dateRanges"
            type="daterange"
            range-separator="至"
            start-placeholder="外呼起始时间"
            end-placeholder="外呼结束时间"
            :unlink-panels="true"
            :default-time="['00:00:00', '23:59:59']"
            @change="dateChange">
          </el-date-picker>
          <el-button
            type="primary"
            :disabled="searchBtnLoading"
            :loading="searchBtnLoading"
            @click="handleFiler"
            style="margin-left: 10px;">
            筛选数据
          </el-button>
        </div>
        <div class="right">
          <el-button type="primary" @click="handleCreateReports">生成报表</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div class="right operation-bar">
          <el-button @click="handleRemove()">删除</el-button>
          <el-button @click="handleSetAtDer">设为贬损者</el-button>
          <el-button @click="handleSetAtPas">设为被动者</el-button>
          <el-button @click="handleSetAtRec">设为推荐者</el-button>
        </div>
      </el-col>
    </el-row>
    <el-table
      stripe
      border
      ref="multipleTable"
      v-loading="tbLoading"
      element-loading-text="拼命加载中"
      :data="orders.list"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"></el-table-column>
      <el-table-column label="单据编号" prop="serverId" align="center"></el-table-column>
      <el-table-column label="分公司办事处" prop="branchOffice" align="center"></el-table-column>
      <el-table-column label="外呼结果" prop="callOutResult" align="center"></el-table-column>
      <el-table-column label="销售环节推荐程度" prop="salesSectionRecommendationLevel" align="center"></el-table-column>
      <el-table-column label="销售环节推荐程度备注" prop="salesSectionRecommendationLevelComment"
                       align="center"></el-table-column>
      <el-table-column label="销售环节推荐理由备注" prop="salesSectionRecommendationScoreReasonsComment"
                       align="center"></el-table-column>
      <el-table-column label="贬损大类" prop="derogatoryCategories" align="center"
                       :formatter="getDeroCategoriesText"></el-table-column>
      <el-table-column label="贬损原因" prop="derogatoryReason" align="center"></el-table-column>
      <el-table-column label="分类" prop="classify" align="center" :formatter="getClassifyText"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="toOrderDetailsView(scope.row)">详情</el-button>
          <el-button type="text" @click="handleRemove(scope.row.serverId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        :current-page.sync="paging.pageIndex"
        :page-size.sync="paging.pageSize"
        layout="sizes, total, prev, pager, next, jumper"
        :total.sync="paging.total"
        :page-sizes="[10, 30, 50, 100]"
        @current-change="pageIndexChange"
        @size-change="pageSizeChange">
      </el-pagination>
    </div>
  </div>
</template>

<script>

  import {
    getNpsReportsOrders,
    removeNpsReportsOrders,
    npsReportsClassify,
    npsCreateReports
  } from "@/service/getData";

  export default {
    data() {
      return {
        dateRanges: [],
        selectedRows: [],
        searchBtnLoading: false,
        tbLoading: false,
        orders: {
          list: [],
          page: {}
        },
        paging: {
          pageIndex: 1,
          pageSize: 10,
          total: 0
        },
        classify: '4'
      }
    },
    computed: {
      selectedRowsIds() {
        return this.selectedRows.map(item => item.serverId)
      }
    },
    beforeRouteEnter(to, from, next) {
      // next回掉在mounted之后执行
      next(vm => {
        const isFromDetails = from.name === 'NpsReportsOrderDetails'
        if(isFromDetails) {
          const statusStr = sessionStorage.getItem('npsReportsOrdersListStatus')
          const status = JSON.parse(statusStr)
          const dateStart = new Date(status.callOutBeginTime)
          const dateEnd = new Date(status.callOutEndTime)
          vm.classify = status.classify
          vm.dateRanges = [dateStart, dateEnd]
          vm.paging.pageSize = status.pageSize
          vm.paging.pageIndex = status.pageIndex
          vm.getNpsReportsOrders().then(() => {
            vm.paging.pageSize = status.pageSize
            vm.paging.pageIndex = status.pageIndex
          })
        }else {
          const query = vm.$route.query || {}
          const t1 = Number(query.t1)
          const t2 = Number(query.t2)
          if(t1 && t2) {
            const dateStart = new Date(t1)
            const dateEnd = new Date(t2)
            vm.dateRanges = [dateStart, dateEnd]
            vm.getNpsReportsOrders()
          }
        }
      })
    },
    methods: {

      initTableOptions() {
        this.paging.pageIndex = 1
        this.paging.total = 0
      },

      // 获取订单列表
      async getNpsReportsOrders() {
        if (!this.checkDateRanges()) {
          return false
        }
        this.tbLoading = true
        try {
          const res = await getNpsReportsOrders({
            callOutBeginTime: this.formatDate(this.dateRanges[0]),
            callOutEndTime: this.formatDate(this.dateRanges[1]),
            page: this.paging.pageIndex,
            size: this.paging.pageSize,
            classify: this.classify
          })
          const data = res.data.data
          if (data.list) {
            this.orders.list = data.list
          }
          if (data.page) {
            this.paging.total = Number(data.page.total)
          }
          this.tbLoading = false
        }
        catch (err) {
          this.tbLoading = false
        }
      },

      // 选择日期
      dateChange(value) {
        this.dateRanges = value
      },

      // 校验日期选择器
      checkDateRanges() {
        if (!this.dateRanges || !this.dateRanges.length) {
          this.$message.closeAll()
          this.$message.warning('请选择外呼起始时间和外呼结束时间！')
          return false
        }
        return true
      },

      // 筛选数据
      handleFiler() {
        this.initTableOptions()
        this.searchBtnLoading = true
        this.getNpsReportsOrders().finally(() => {
          this.searchBtnLoading = false
        })
      },

      // 删除前校验
      handleRemove(serverId) {
        const orders = serverId ? [serverId] : this.selectedRowsIds
        const n = orders.length
        if (!n) {
          this.$message.closeAll()
          this.$message.warning('请选择需要删除的订单！')
          return false
        }
        const tips = n === 1 ? '确定删除该条订单？' : '确定删除所有选中的订单？'
        const title = ''
        this.$confirm(tips, title, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.removeNpsReportsOrders(orders)
        }).catch(() => {
          // this.handleClearSelection()
        });
      },

      // 删除订单
      removeNpsReportsOrders(ordersArray) {
        removeNpsReportsOrders(ordersArray).then(res => {
          // this.initTableOptions()
          this.getNpsReportsOrders()
          this.$message.success(res.data.data)
        }).catch(err => {
          this.$message.error('删除订单时出错，请重新操作！')
        }).finally(() => {
          this.handleClearSelection()
        })
      },

      // 设为贬损者
      handleSetAtDer() {
        this.manuallyClassify('0')
      },

      // 设为被动者
      handleSetAtPas() {
        this.manuallyClassify('1')
      },

      // 设为推荐者
      handleSetAtRec() {
        this.manuallyClassify('2')
      },

      // 设置订单分类
      manuallyClassify(classify) {
        if (!this.selectedRowsIds.length) {
          this.$message.closeAll()
          this.$message.warning('请选择订单！')
          return false
        }
        npsReportsClassify(this.selectedRowsIds, classify).then(res => {
          // this.initTableOptions()
          this.getNpsReportsOrders()
          this.$message.success(res.data.data)
        }).catch(err => {
          this.$message.error(err.data.data)
        }).finally(() => {
          this.handleClearSelection()
        })
      },

      // 生成报表
      handleCreateReports() {
        if (!this.checkDateRanges()) {
          return false
        }
        const query = this.$route.query
        const id = query.id
        const loading = this.$loading({
          lock: true,
          text: '正在生成报表...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.5)'
        })
        let params = {
          callOutBeginTime: this.formatDate(this.dateRanges[0]),
          callOutEndTime: this.formatDate(this.dateRanges[1])
        }
        if (id) {
          params.id = id
        }
        npsCreateReports(params).then(res => {
          const data = res.data.data
          if(!data) {
            this.$message.error('未知错误！')
            return
          }
          const id = JSON.parse(data).result
          this.$message({
            type: 'success',
            message: '生成报表成功！',
            duration: 1000,
            onClose: () => {
              this.$router.push({
                name: 'NpsReportDetails',
                params: {id}
              })
            }
          });
        }).catch(err => {
          this.$message.error('生成报表失败，请稍后重试！')
        }).finally(() => {
          loading.close()
        })
      },

      // 跳转订单详情页
      toOrderDetailsView(row) {
        const status = {
          callOutBeginTime: this.dateRanges[0].getTime(),
          callOutEndTime: this.dateRanges[1].getTime(),
          pageIndex: this.paging.pageIndex,
          pageSize: this.paging.pageSize,
          classify: this.classify
        }
        sessionStorage.setItem('npsReportsOrdersListStatus', JSON.stringify(status))
        this.$router.push({
          name: 'NpsReportsOrderDetails',
          params: {
            id: row.serverId.toString()
          },
          // query: {
          //   t1: this.dateRanges[0].getTime(),
          //   t2: this.dateRanges[1].getTime()
          // }
        })
      },

      // 当前页改变
      pageIndexChange(value) {
        console.log('pageIndexChange: %o', value)
        this.paging.pageIndex = value
        this.getNpsReportsOrders()
      },

      // 页面容量改变
      pageSizeChange(value) {
        console.log('pageSizeChange: %o', value)
        this.paging.pageIndex = 1
        this.paging.pageSize = value
        this.getNpsReportsOrders()
      },

      // 多选
      handleSelectionChange(value) {
        this.selectedRows = value
      },

      // 清空选择
      handleClearSelection() {
        this.$refs.multipleTable.clearSelection();
      },

      // 贬损大类
      getDeroCategoriesText(row) {
        const items = ['其他', '卖场', '安装', '送货', '品牌', '服务', '产品']
        return items[row.derogatoryCategories]
      },

      // 分类
      getClassifyText(row) {
        const items = ['贬损者', '被动者', '推荐者', '未分类', '全部']
        return items[row.classify]
      },

      // 日期格式化
      formatDate(date) {
        return this.$date.format(new Date(date), 'YYYY-MM-DD HH:mm:ss')
      }

    }
  }
</script>

<style lang="scss" scoped>

  .left {
    float: left;
  }

  .right {
    float: right;
  }

  .filter-bar {
    padding-bottom: 20px;
    border-bottom: 1px solid #dcdfe6;
  }

  .operation-bar {
    padding: 20px 0;
  }

</style>
